package lol.clann.minecraft.springboot.plugin.bukkit.command.parameter;

import lol.clann.minecraft.springboot.plugin.bukkit.command.CommandContext;
import lol.clann.minecraft.springboot.api.bukkit.command.resolver.CommandResolver;
import lol.clann.minecraft.springboot.plugin.bukkit.command.resolver.CommandResolvers;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.ToString;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;

import java.lang.reflect.Type;

/**
 *
 * @author pyz
 * @date 2019/5/6 10:07 PM
 */
@Getter
@ToString
@Builder
public class FlagParameter {
    private int index;
    @NonNull
    private String flag;
    @Builder.Default
    private boolean required = true;
    @NonNull
    private CommandResolver resolver;
    private Type type;

    public Object resolve(CommandSender commandSender, CommandContext context) {
        String value = context.getFalgMap().get(flag);
        if (resolver == CommandResolvers.getBooleanFlagResolver()) {
//            解析boolean flag
            return resolver.resolve(commandSender, value, type);
        }
        if (value == null) {
            if (required) {
                throw new CommandException(String.format("缺少flag参数: " + flag));
            } else {
                return null;
            }
        }
        return resolver.resolve(commandSender, value, type);
    }
}
